package com.ustcinfo.study.hive.r1.panwentao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Describe:
 * Author: pwt
 * Date: 2018/8/3
 */

public class HiveConnection {
	// hive链接地址
	private static String url="jdbc:hive2://node1:10000/default";
	// hive用户名
	private static String userName="root";
	// hive密码
	private static String passwd="";
	// hive驱动
	private static String driver="org.apache.hive.jdbc.HiveDriver";
	private static Connection conn=null;
	private static Statement statement=null;
	private static ResultSet rs=null;
	private static String sql="select domain_name,count(*) from dns_pwt group by domain_name";
	
	
	public static void main(String[] args) throws SQLException {
		// 加载驱动
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			// 获取连接
			conn=DriverManager.getConnection(url,userName,passwd);
			if(conn!=null) {
				System.out.println("连接hive成功");
			}else {
				System.out.println("连接hive失败");
			}
			statement=conn.createStatement();
			System.out.println("正在查询...");
			// 查询每个域名出现的次数
			rs=statement.executeQuery(sql);

			while(rs.next()) {
				String domain_name=rs.getString(1);
				int sum=rs.getInt(2);
				System.out.println(domain_name+"         "+sum);
			}
			System.out.println("查询成功！");
		} catch (SQLException e) {
			System.out.println("连接hive异常");
			e.printStackTrace();
		}finally {
			if(conn!=null) {
				conn.close();
			}
			if(statement!=null) {
				statement.close();			
			}
			if(rs!=null) {
				rs.close();
			}
		}
		
			
			
		
	}

}
